<template>
	<view>
		<u-navbar :isBack="false" title="快速下单" title-color="#333" back-icon-color="#333"></u-navbar>
		
		<view style="padding: 24rpx;">
			<u-form ref="form" class="detail-form" label-width="200rpx" :label-style="{ color: '#333333' }"
				:model="formModal">
				<public-form-group>
					<!-- <u-form-item label="称呼" prop="name">
					  <input class="u-flex-1" v-model="formModal.nickname" type="text" placeholder="请填写称呼"/>
					</u-form-item>
					<u-form-item label="联系电话" prop="mobile">
					  <input class="u-flex-1" v-model="formModal.mobile" type="number" placeholder="请填写您的联系电话"/>
					</u-form-item>
					<u-form-item label="服务地址" prop="grade">
						<view class="u-flex u-flex-1 link-active" @click="toMapSelection">
							<input class="u-flex-1" v-model="formModal.location_str" type="text" placeholder="请选择服务地址" disabled/>
							<u-icon name="map" color="#18cba2" label-size="60"></u-icon>
						</view>
					</u-form-item>
					<u-form-item label="详细地址" prop="name">
					  <input class="u-flex-1" v-model="formModal.location_detail" type="text" placeholder="请填写服务详细地址"/>
					</u-form-item> -->
					<u-form-item>
						<view class="u-flex u-flex-1 link-active" @click="toAddress">
							<view style="display: flex; flex-direction: column; flex: 1;">
								<text style="font-size: 32rpx; font-weight: bold; overflow: hidden; 
								text-overflow: ellipsis; white-space: nowrap; width: 600rpx;">{{formModal.location_detail}}</text>
								<view style="display: flex; flex-direction: row; color: dimgray; font-size: 26rpx;">
									<text>{{formModal.nickname}}</text>
									<text style="margin-left: 20rpx;">{{formModal.mobile}}</text>
								</view>
							</view>
							<u-icon name="arrow-right"></u-icon>
						</view>
					</u-form-item>
					<u-form-item label="服务时间" prop="practice">
						<view class="u-flex u-flex-1 link-active">
							<!-- <picker class="u-flex-1" mode="date" :value="serviceDate" @change="onDateChange">
			      <view>{{ serviceDate }}</view>
			    </picker>
			    <picker class="u-flex-1" mode="time" :value="serviceTime" @change="onTimeChange">
			      <view> {{ serviceTime }}</view>
			    </picker> -->
							<picker class="u-flex-1" mode="multiSelector" :value="serviceDateIndexes" range-key="key"
								:range="serviceDate" @change="onDateChange">
								<view>
									<text>{{serviceDate[0][serviceDateIndexes[0]].value}}
										{{serviceDate[1][serviceDateIndexes[1]].value}}</text>
								</view>
							</picker>
							<u-icon name="arrow-right"></u-icon>
						</view>
					</u-form-item>
					<u-form-item label="需求工种" prop="work">
						<view class="u-flex u-flex-1 link-active" @click="craftShowClick()">
							<label class="u-flex-1">{{craftText}}</label>
							<u-icon name="arrow-right"></u-icon>
						</view>
					</u-form-item>
					<u-form-item>
						<view style="display: flex; flex-direction: row; width: 95vw; align-items: center;">
							<text>预约金</text>
							<u-radio-group v-model="value" @change="radioGroupChange" active-color="#0daff0"
								style="margin-left: 100rpx;">
								<u-radio name="pay">
									预付
								</u-radio>
								<u-radio name="notpay">
									面议
								</u-radio>
							</u-radio-group>
						</view>
					</u-form-item>
					<u-form-item v-show="isDeposit" prop="ss">
						<view class="u-flex u-flex-1"
							style="background-color: #f6f6f6; border-radius: 10rpx; padding: 0 20rpx;">
							<input class="u-flex-1" v-model="formModal.deposit" type="number" placeholder="请输入预约金" />
							<text>元</text>
						</view>
					</u-form-item>
				</public-form-group>
				<u-gap height="24" bg-color="#F5F5F5"></u-gap>
				<public-form-group>
					<u-form-item label="需求描述" prop="introduce" label-position="top">
						<textarea v-model="formModal.description" auto-height maxlength="500" placeholder="请输入您遇到的问题"
							class="u-flex-1" style="min-height: 280rpx; line-height: 1.5em" />
					</u-form-item>
					<u-form-item label="需求备注" prop="name">
						<input class="u-flex-1" v-model="formModal.memo" type="text" placeholder="如若需要师傅自带工具请备注说明" />
					</u-form-item>
			
					<u-form-item label="图片描述" prop="" label-position="top">
						<view style="width: 100%">
							<u-upload @on-choose-complete="onChooseComplete" @on-remove="onImgRemove"
								:show-upload-list="true" :auto-upload="false" :file-list="fileList" :show-progress="true"
								:deletable="true" max-count="10"></u-upload>
						</view>
					</u-form-item>
				</public-form-group>
			</u-form>
		</view>
		
		<view style="background-color: #fbfbfb;">
			<button class="u-reset-button confirm-btn" @tap="submit">提交</button>
			<view class="safe-area-inset-bottom"></view>
		</view>

		<!-- 工种列表 -->
		<u-select v-model="craftShow" mode="mutil-column-auto" label-name="name" value-name="id" :list="craftList"
			@confirm="craftCofirm"></u-select>

		<u-tabbar v-model="current" :list="tabbar" active-color="#0daff0"  :mid-button="true"></u-tabbar>
	</view>
</template>

<script>
	import { getTabbarConfig } from '@/common/tabbar';
	import configUrl from 'utils/config.js';
	import { request } from 'utils/request.js';
	export default {
		name: "FinanceRegister",
		data() {
			return {
				current: 2,
				tabbar: getTabbarConfig(true),
				
				craftList: [],
				value: '20',
				positioning: configUrl.appurlImg + '/app/ddingwei.png',
				craftShow: false,
				isDeposit: false,
				depositLabelText: "",

				serviceDate: [],
				serviceDateIndexes: [0, 0],
				strServiceData: "",

				craftText: "请选择需求工种",

				formModal: {
					nickname: "请选择或添加您的服务地址",
					mobile: "",
					longitude: 0,
					latitude: 0,
					location_str: "服务地址",
					location_detail: "服务地址",
					starttime: "2024-1-8 04:53",
					deposit: 0,
					memo: "",
					description: "",
					desc_image: "",
					craft_id: 1,
				},
				rules: {},
				fileList: [],
				fileListUrls: [],
				header: {
					'token': ''
				},
				preSelectCraftId: 0,
				isdisabled:false
			};
		},
		onLoad(e) {
			uni.$on('userAddressAdd', (e) => {
				console.log('userAddressAdd: ', e);
				this.formModal.nickname = e.nickname;
				this.formModal.mobile = e.mobile;
				this.formModal.longitude = e.longitude;
				this.formModal.latitude = e.latitude;
				this.formModal.location_str = e.region;
				this.formModal.location_detail = e.addrdetails
				this.addressData = e;
			});
			if (e != null) {
				this.preSelectCraftId = e.cid;
			}
		},
		onShow() {
			this.isdisabled=false
		},
		onReady() {
			var self = this;
			// this.$refs.form.setRules(this.rules);
			let token = uni.getStorageSync('token');
			let now = new Date();
			now.setDate(now.getDate() - 1);
			this.serviceDate = [
				[],
				[]
			];
			for (let i = 0; i < 7; i++) {
				now.setDate(now.getDate() + 1);
				let dF = "";
				switch (i) {
					case 0:
						dF = "(今天) ";
						break;
					case 1:
						dF = "(明天) ";
						break;
					case 2:
						dF = "(后天) ";
						break;
				}
				this.serviceDate[0].push({
					key: dF + (now.getMonth() + 1) + "-" + now.getDate(),
					value: now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate()
				});
			}
			this.serviceDateIndexes = [0, 0];
			this.serviceDate[1].push({
				key: "8:00-10:00",
				value: "8:00"
			});
			this.serviceDate[1].push({
				key: "10:00-12:00",
				value: "10:00"
			});
			this.serviceDate[1].push({
				key: "12:00-14:00",
				value: "12:00"
			});
			this.serviceDate[1].push({
				key: "14:00-16:00",
				value: "14:00"
			});
			this.serviceDate[1].push({
				key: "16:00-18:00",
				value: "16:00"
			});
			this.serviceDate[1].push({
				key: "18:00-20:00",
				value: "18:00"
			});
			this.formModal.starttime = this.serviceDate[0][this.serviceDateIndexes[0]].value + " " + this.serviceDate[1][
				this.serviceDateIndexes[1]
			].value;
			if (token) {
				this.header.token = token;
				console.log(this.header)
			}
			
			request.postWithToken({
				url: '/merchant/getGoodsCategory',
			}).then(res=>{
				console.log(res)
				self.craftList = res.data;
			})
			
			// commonApi.getDefaultAddress().then((res) => {
			// 	if (res != null) {
			// 		self.formModal.nickname = res.nickname;
			// 		self.formModal.location_str = res.region,
			// 			self.formModal.location_detail = res.addrdetails,
			// 			self.formModal.longitude = res.longitude,
			// 			self.formModal.latitude = res.latitude,
			// 			self.formModal.mobile = res.mobile
			// 	}
			// 	console.log(self.formModal);
			// });

		},
		methods: {
			craftShowClick(){
				console.log(333333)
				this.craftShow = true
			},
			// 选中任一radio时，由radio-group触发
			radioGroupChange(e) {
				this.isDeposit = e == 'pay';
				if (e != 'pay') {
					this.formModal.deposit = 0;
				}
			},
			craftCofirm(e) {
				console.log('confirm', e);
				this.formModal.craft_id = e[0].value;
				this.craftText = e[0].label;
				this.craftShow = false;
			},
			depositConfirm(e) {
				console.log(e);
				this.formModal.deposit = e[0].value;
				this.depositLabelText = e[0].label;
				this.depositShow = false;
			},
			onDateChange(e) {
				let indexes = e.detail.value;
				this.serviceDateIndexes = e.detail.value;
				this.formModal.starttime = this.serviceDate[0][this.serviceDateIndexes[0]].value + " " + this.serviceDate[
					1][this.serviceDateIndexes[1]].value;
				console.log(this.formModal.starttime);
			},
			uploadimg() {
				let _this = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						_this.uploadFilePaths(res.tempFilePaths[0]);
					}
				});
			},
			uploadFilePaths(url) {
				let _this = this;
				uni.uploadFile({
					url: configUrl.appurl + `/index/uploadOrderImage`, //仅为示例，非真实的接口地址
					filePath: url,
					name: 'file',
					header: {
						'token': uni.getStorageSync('token'),
					},
					success: (uploadFileRes) => {
						console.log('uploadFileRes：', uploadFileRes);
						let result = uploadFileRes.data;
						if (uploadFileRes.statusCode == 401) {
							uni.removeStorageSync('token')
							uni.navigateTo({
								url: '/pages/auth/Login',
							})
						}
						if (uploadFileRes.statusCode == 200) {
							result = JSON.parse(result);
							if (result.code == 1) {
								console.log('返回信息：', result);
								_this.portrait_image = result.data.fullurl;
							} else {
								uni.showToast({
									title: result.msg,
									duration: 2000,
									icon: "none",
								});
							}
						}
					}
				});
			},
			submit() {
				let self = this;
				this.formModal.desc_image = this.fileListUrls.join(",");
				if (this.formModal.deposit <= 0 && this.isDeposit) {
					uni.showToast({
						title: "预付金额不正确",
						duration: 3000,
						icon: 'error'
					});
					return;
				}
				if(this.formModal.longitude == 0 || this.formModal.latitude == 0){
					uni.showToast({
						title: "请选择服务地址",
						duration: 3000,
						icon: 'error'
					});
					return;
				}
				this.formModal.is_deposit = this.value;
				this.isdisabled = true;
				request.postWithToken({
					url: '/order/createOrder',
					data: self.formModal
				}).then(res=>{
					console.log(res)
					uni.showToast({ title: res.msg, duration: 2000, icon: "none" });
					if(res.code == 1){
						let redirectUrl = '/pages/menu/order';
						// 如果需要交定金，下单成功后跳转到支付页面
						if (this.isDeposit && this.value == 'pay') {
							redirectUrl = '/pages/pay/payment?orderId=' + res.data;
							setTimeout(() => {
								uni.navigateTo({
									url: redirectUrl
								})
							}, 800);
						}
						setTimeout(() => {
							uni.switchTab({
								url: redirectUrl
							})
						}, 800);
					}
					// self.craftList = res.data;
				});
				
				// this.$refs.form.validate((valid) => {
				// 	if (valid) {
						// orderApi.createOrder(self.formModal).then((res) => {
						// 	uni.showToast({
						// 		title: "订单创建成功",
						// 		duration: 2000,
						// 		icon: "none",
						// 	});
						// 	let redirectUrl = '/pages/users/Order';
						// 	// 如果需要交定金，下单成功后跳转到支付页面
						// 	if (this.isDeposit) {
						// 		redirectUrl = '/pages/users/Payment?orderId=' + res;
						// 	}
						// 	setTimeout(() => {
						// 		uni.navigateTo({
						// 			url: redirectUrl
						// 		})
						// 	}, 1500);
						// });
				// 	}
				// 	console.log('valid: ', valid)
				// });
			},
			onImgRemove(index, lists, name) {
				this.fileListUrls.splice(index, 1);
			},
			onChooseComplete(lists, name) {
				this.fileList = [];
				this.fileListUrls = [];
				let self = this;
				lists.forEach(img => {
					request.uploadFileImg({
						url: '/common/upload',
						data: img.url,
					}).then(res => {
						console.log('data-', res);
						// that.shopForm.logo = res;
						self.fileListUrls.push(res);
					});
					return;
					uni.uploadFile({
						// url: configUrl.appurl + `/user/uploadOrderImage`,
						url:  configUrl.appurl + '/common/upload',
						filePath: img.url,
						name: 'file',
						header: {
							'token': uni.getStorageSync('token'),
						},
						success: (uploadFileRes) => {
							console.log('uploadFileRes：', uploadFileRes);
							let result = uploadFileRes.data;
							if (uploadFileRes.statusCode == 401) {
								uni.removeStorageSync('token')
								uni.navigateTo({
									url: '/pages/auth/Login',
								})
							}
							if (uploadFileRes.statusCode == 200) {
								result = JSON.parse(result);
								if (result.code == 1) {
									console.log('返回信息：', result.data);
									// self.fileList.push(result.data.fullurl);
									self.fileListUrls.push(result.data.url);
								} else {
									uni.showToast({
										title: result.msg,
										duration: 2000,
										icon: "none",
									});
								}
							}
						}
					});
				});
			},
			toAddress() {
				let self = this;
				// uni.$off("returnAddress");
				// uni.$on("returnAddress", (info) => {
				// 	self.formModal.nickname = info.nickname;
				// 	self.formModal.mobile = info.mobile;
				// 	self.formModal.longitude = info.longitude;
				// 	self.formModal.latitude = info.latitude;
				// 	self.formModal.location_str = info.location_str;
				// 	self.formModal.location_detail = info.location_detail
				// });
				// uni.navigateTo({
				//   url: '/pages/users/MyAddress'
				// });
				uni.navigateTo({
					url: '/pages/user/userAddress'
				});
			}
		},
	};
</script>

<style lang="scss" scoped>
	// @import "static/css/public-custom-form.scss";

	.header-container {
		width: 100vw;
		display: flex;
		flex-direction: column;
		background-color: #196ae3;

		.app-title {
			padding: 0 25rpx;
			font-size: 32rpx;
			font-weight: bold;
			padding-left: 30rpx;
			color: #000;
		}
	}

	.upload-btn {
		position: relative;
		width: 140rpx;
		height: 140rpx;
		border: 0.5px solid #999;
		border-radius: 8rpx;

		&::before,
		&::after {
			position: absolute;
			left: 50%;
			top: 50%;
			display: block;
			width: 50%;
			border-top: 0.5px solid #999;
			content: '';
			transform: translate(-50%, -50%);
		}

		&::after {
			transform: translate(-50%, -50%) rotate(90deg);
		}
	}

	.tips-text {
		font-size: 24rpx;
		color: #b2b2b2;
	}

	.confirm-btn {
		margin: 22rpx;
		width: calc(100vw - 44rpx);
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		color: #fff;
		background-color: #0daff0;
		// border-radius: 999px;
		border-radius: 24rpx;

		&:active {
			background-color: lighten(#0daff0, 10%);
		}
	}

	page {
		background: #F5F5F5 !important;
	}
</style>